package controllers

import (
	"newAi/new_web/models"
	"github.com/astaxie/beego"
	"strings"
)

type TplController struct {
	BaseController
}

func (self *TplController) List() {
	self.Data["pageTitle"] = "模板管理"
	self.display()
}

func (self *TplController) Explain() {
	self.Data["pageTitle"] = "使用说明"
	self.display()
}

func (self *TplController) TplAdd() {
	if self.isOrg == true {
		self.SetUserGroup(self.userId)
	} else {
		self.SetAllGroup()
	}
	isCopy, _ := self.GetBool("isCopy")
	if isCopy {
		self.Data["isCopy"] = true
		self.Data["copyId"], _ = self.GetInt64("copyId")
	}
	self.Data["pageTitle"] = "新增交互流程"
	self.Data["tplList"],_ = models.GetAllTpls(self.userId)
	self.display()
}

func (self *TplController) TplEdit() {
	self.Data["pageTitle"] = "编辑交互流程"
	if self.isOrg == true {
		self.SetUserGroup(self.userId)
	} else {
		self.SetAllGroup()
	}
	id, _ := self.GetInt("id", 0)
	tpl, _ := models.TplGetById(id)
	row := make(map[string]interface{})
	row["id"] = tpl.Id
	row["owner_id"] = tpl.Owner_id
	row["tpl_desc"] = tpl.Tpl_desc
	row["tpl_name"] = tpl.Tpl_name
	row["parent_id"] = tpl.Parent_id
	row["root_id"] = tpl.Root_id
	self.Data["tplList"],_ = models.GetAllTpl(self.userId,tpl.Root_id)
	self.Data["tpl"] = row
	self.display()
}

//节点内容
func (self *TplController) ContentTable() {

	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	//查询条件
	filters := make([]interface{}, 0)
	result, count := models.ProcessContentGetList(page, self.pageSize, "process_content", filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["order"] = v.Ai_order
		row["type"] = v.Type
		row["content"] = v.Content

		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

//列表
func (self *TplController) TplTable() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit
	user_group, err := models.UserGroupIdName()
	self.CheckError(err)
	//查询条件
	filters := make([]interface{}, 0)
	if self.isOrg == true {
		filters = append(filters, "owner_id", self.userId)
	}
	result, count := models.TplGetList(page, self.pageSize, "tpl", filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["tpl_name"] = v.Tpl_name
		for _, b := range user_group {
			if v.Owner_id == b.Id {

				row["owner_id"] = b.LoginName
			}
		}
		row["tpl_desc"] = v.Tpl_desc

		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *TplController) AjaxSave() {
	//self.ajaxMsg("分组名已经存在", MSG_ERR)
	//Process_id, _ := self.GetInt("id")

	Tpl := new(models.AiTpl)

	Tpl.Tpl_name = strings.TrimSpace(self.GetString("tpl_name")) //流程名称
	Tpl.Tpl_desc = strings.TrimSpace(self.GetString("tpl_desc"))
	Tpl.Owner_id, _ = self.GetInt("owner_id")
	Tpl.Parent_id, _ = self.GetInt64("parent_id", 0)

	if (Tpl.Parent_id != 0) {//不等于0，说明它是某某的子节点
		tplOne,_ := models.TplGetById(int(Tpl.Parent_id))
		if tplOne.Parent_id != 0 {//说明这个的父节点有父节点，那么它的根节点就是通用的
			Tpl.Root_id = tplOne.Root_id
		}else {//说明这个的父节点没有父节点，那么它的id就是通用的根节点
			Tpl.Root_id = tplOne.Id
		}
	}

	//任务节点
	//打断。0支持打断，1支持不打断，2支持按需求打断

	//判断 是否存在 ID， 如果有ID的话，就进行update
	if i, _ := self.GetInt64("id"); i != 0 {
		Tpl.Id = i
		if err := Tpl.Update(); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)
	}
	//如果没有ID  ，就进行增加的
	tplId, err := models.TplAdd(Tpl)
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
		return
	}
	q, _ := self.GetBool("isCopy")
	var copyId, _ = self.GetInt64("copyId")
	if q == true {
		//创建默认话术
		err = models.CopyTpl(copyId, tplId)
		if err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
			return
		}
		self.ajaxMsg("", MSG_OK)
	}
	//创建默认话术
	err = self.CreateDefaultTpl(tplId)
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
		return
	}

	self.ajaxMsg("", MSG_OK)

}

func (self *TplController) CreateDefaultTpl(tplId int64) error {
	var err = setStart(tplId) //创建静音
	if err != nil {
		models.ErrorLog(err)
		return err
	}
	return nil
}

func addContent(contents string, process_id int64, order int) {
	content := new(models.AiProcessContent)

	content.Content = contents
	content.Process_id = process_id
	content.Type = 1
	content.Ai_order = order
	content.Audio_path = " "
	_, err := models.ProcessContentAdd(content)
	if err != nil {
		beego.Error(err)
	}
}

//设置开场白
func setStart(id int64) error {

	//
	Process := new(models.AiProcess)

	Process.Node = 0                                 //任务节点
	Process.Node_type = 1                            //节点类型，0为语音文件，1为TTS文字
	Process.Node_content = "您好，我是智能机器人，有什么可以为您服务的吗？" //节点内容，根据类型，文字或者录音文件绝对地址
	Process.Node_name = "开场白"
	Process.Owner_tpl_id = id
	Process.Mode = 1
	//归属模板id
	defaultProcess(Process)

	processId, err := models.ProcessAdd(Process)
	if err != nil {
		return err
	}
	addContent(Process.Node_content, processId, 0)
	err = setMute(id, processId, -2) //创建静音
	err = setMute(id, 0, -5)         //创建静音

	if err != nil {
		models.ErrorLog(err)
		return err
	}
	err = setUnmatched(id, processId, -3) //创建全局不匹配
	err = setUnmatched(id, 0, -6)         //创建全局不匹配

	if err != nil {
		models.ErrorLog(err)
		return err
	}
	if err != nil {
		return err
	}
	return nil
}

//设置全局变量
func (self *TplController) AddGlobal() {
	id, _ := self.GetInt64("id")
	processId, _ := self.GetInt64("processId")
	pid, process, _ := models.ProcessNoIdGetByTplId(id, -5)
	process.Owner_tpl_id = id
	process.Parent_id = processId
	process.Node = -2
	var err = copyGlobalNode(process, pid) //创建静音
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
		return
	}
	pid, process, _ = models.ProcessNoIdGetByTplId(id, -6)
	process.Owner_tpl_id = id
	process.Parent_id = processId
	process.Node = -3
	err = copyGlobalNode(process, pid) //创建全局不匹配
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
		return
	}
	self.ajaxMsg("", MSG_OK)
}

//设置静音
func setMute(id int64, parent_id int64, node int) error {

	//
	Process := new(models.AiProcess)

	Process.Node = node                //任务节点
	Process.Node_type = 1              //节点类型，0为语音文件，1为TTS文字
	Process.Node_content = "不好意思，没听清。" //节点内容，根据类型，文字或者录音文件绝对地址
	Process.Node_name = "当前静音"
	Process.Owner_tpl_id = id //归属模板id
	defaultProcess(Process)
	Process.Parent_id = parent_id

	processId, err := models.ProcessAdd(Process) //生成process 返回id
	if err != nil {
		return err
	}

	addContent(Process.Node_content, processId, -2) //生成 process_content

	return nil
}

//设置静音以及不匹配
func copyGlobalNode(Process *models.AiProcess, id int64) error {

	processId, err := models.ProcessAdd(Process) //生成process 返回id
	if err != nil {
		beego.Error("err", err)
		return err

	}
	processContent, err := models.ProcessContentByProcess(id)
	if err != nil {
		beego.Error("err", err)
		return err
	}

	processContent.Content = Process.Node_content
	processContent.Process_id = processId
	_, err = models.ProcessContentAdd(processContent)
	if err != nil {
		beego.Error(err)
	}

	return nil
}

//设置不匹配
func setUnmatched(id int64, parent_id int64, node int) error {

	//
	Process := new(models.AiProcess)

	Process.Node = node                //任务节点
	Process.Node_type = 1              //节点类型，0为语音文件，1为TTS文字
	Process.Node_content = "我不明白您说什么。" //节点内容，根据类型，文字或者录音文件绝对地址
	Process.Node_name = "当前不匹配"
	Process.Owner_tpl_id = id //归属模板id
	defaultProcess(Process)
	Process.Parent_id = parent_id

	processId, err := models.ProcessAdd(Process)
	if err != nil {
		return err
	}
	addContent(Process.Node_content, processId, -3)

	return nil
}

//初始化 说话时长
func defaultProcess(process *models.AiProcess) {
	process.Min_speak_ms = 100
	process.Min_pause_ms = 500
	process.Max_waiting_ms = 5000
	process.Max_recording_ms = 10000
}

func (self *TplController) AjaxDel() {
	Tpl_id, _ := self.GetInt("id")
	Tpl, _ := models.TplGetById(Tpl_id)

	if err := Tpl.Delete(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	err := models.QueryProcessStartNode(Tpl_id)
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	err = models.DeleteProcess(Tpl_id)
	if err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}

	self.ajaxMsg("", MSG_OK)
}

//
//func (self *TplController) Upload() {
//
//	path, err := self.UploadFile("upload/", "uploadField")
//	if err == nil {
//		self.ajaxMsg(path, MSG_OK)
//	} else {
//		self.ErrorLog(err)
//	}
//
//}
